<?php
/**
 * Created by PhpStorm.
 * User: 戎大富
 * Date: 2018/6/13
 * Time: 10:40
 */
namespace app\api\controller;
use think\Controller;
use think\Db;

class  Base extends Controller {
    protected $_error;
    protected $_header;//用户的请求头信息
    protected $config = array(
        'partner'=>'2088621781822784',//用不着
        'seller_id'=>'admin@bagepanzi.com',//用不着
        'sign_type'=>'RSA2',// 直接写死了
        'it_b_pay'=>'10m',//用不着
        'md5'=>'djqm7budkdlki6a76yasuyb9s1riiu1j',//用不着
        'ali_public'=>'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAo0orbhHsCzT8i8lirEeRVYHL9V/77IM/Fx96IM0mX8oRg9mtYQW94+wDdUKJzBhVkxLEJTH/zGrBIUxdlzu8eFfiH8JBhB+IVQQ/CGo4eKnBi9w1telzjgJKqKEA9cs5wuzrP1NTpUvQBGXK4cy6oU6d/vqBmwF7ZRmyJPmHbTlkftFcXVbTxKI+Ercn719UQ3TvboT/mAO/JO6rVxCYzSL+wPT49d3JGuSVxBVoiPE1gp0pt+mIuBHKDYhog6zywhndjgHaW5ShOK5FLYzEYobWaGqcjSs+EzcOyo6fGwitP9ng9KO0KCB86z7PxW5yDVnkpTfxcQ1pq2BU5rt3HQIDAQAB',
        'public_key'=>"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyODxdRKXOT6aj9bmV2AEz4LFtBBqfd1PnxL+4ft9kyi/hy43Wgs54O2BmpKZiXHTy4pAbidkr3AzEMmH21S6PWX59q+gyu9AZtL+/9HOJ9b+I1ViJt5VXYrcqpTV5HqqgdNx53y5ud7S5F8gyyZX6voh3B4rVD4MOqOypRKor5/yklGfQKImP31DwvgvDOb8oPIIWRs92gTLf3/2wxZU69U4eZF+m1k5CtcVQxrhXv61vSUNCjuU0h2PCsInx65tIV7kA+JuGqeqhMUUKjZSmJ3hWjcXf+7TWhpLqc0GSUbO+vNp6g5WmE4EJ+bwYJ55tqzkfp2cTfdhEaeuYx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sfzDLCE3MCgYBW7u0uNUABW/T2nJNO/ZLzrOh5PNYJPV1RW7qOEYIdZ2A+/bjEyuYWyWi7/shbZav+keXRW+/8/Hjgpq2QQvIySdX7patu0UW8e8ViZ+5vthpNJLkh817qaVhLqmAJlQa0YI+riHurs+VbuCDWKuuTHPClEfQ+06G9ViFVTJ6YLQKBgQDBholLss24H76BmTURNbWY5aOL6sSqaT/H0mIG453oOmU0IVOboQQuXBC93JfBDH78sFogrUcUTUX3rm6kP1xkjmfS6/JF14R9JRdj4lymR1swf/VIJaVPvXPArDSC9uIm8LKJchcPVda6kDXU84hEZQf9zTd5uR3iRzG1kSJnLQKBgQCoUGqQZqmBFoAcLm1C8GTNEN9xiLaTPtA6hEHhxX0tuS1lxVt5RZpgrHisXH52HOqKnC0OYcG1xgFU98ITEJttakADXZq2tckOql6fOwfy4f96VtA8EwZczn+LonzAFJuB7pm49wy1H1pLc4ySzQc+kRSjXV4Hgfn5TAHdACPjIQ=='
    );
    // 定义配置项（这是房产的了）
    private $config2=array(
        'APPID'              => 'wx17defefa924f0c04', // 微信支付APPID.
        'MCHID'              => '1536327111', // 微信支付MCHID 商户收款账号
        'KEY'                => 'kZkEDXEHH8yqXXEuoKVpVv2WQKyx5Agj', // 微信支付KEY
        'APPSECRET'          => '897764b0ae45c439b01eb7b437b6a028', // 公众帐号secert (公众号支付专用)
        'NOTIFY_URL'         => 'http://house.xuanwumobile.com/api/Order/huidiaoWx', // 接收支付状态的连接

    );
    // 构造函数
    public function _initialize(){
        // 如果配置项为空 则直接返回

    }

    /**
     * 验证唯一——单点登录(禁用禁止访问和判断会员状态)
     * user_id，time，salt，value
     * @return string
     */
    public  function checkAll($uid,$time,$value,$reqKey){
        if($uid == 0){
            return true;
        }else{
            $user = Db::table('up_u_user')->where('user_id',$uid)
                ->field('user_auth,user_auth_end,user_status,user_token')->find();
            if($user['user_status'] == 3){//禁用
                return false;
            }
            //------------------------------------------------------
            if($user['user_auth'] > 1){
                $today = date('Y-m-d');
                if($user['user_auth_end'] < $today){
                    Db::table('up_u_user')->where('user_id',$uid)->update(['user_auth'=>1]);
                }
            }
            //------------------------------------------------------
            $token = $user['user_token'];
            $appId = "A60824974958171";
            $appkey = "9KI962A0-YF56-W4OU-9635-6D57B0CCE811";
            $myreqKey = md5($appId . 'XW' . $appkey . 'XW' . $time);
            $myvalue = md5($uid . 'XW' . $token . 'XW' . $time);
            if($myvalue != $value || $myreqKey != $reqKey){
                return false;
            }else{
                return true;
            }
        }
    }

    /**
     * 云之讯发送短信
     * @param $phone
     * @param $num
     * @return mixed
     */
    public function duaxin($phone,$num){
//        header("Content-type: text/html; charset=utf-8");
        $body_json = array(
            'sid'=>'4ca801e70403f961f07e4f41c4574293',
            'token'=>'6d66d03c8be11e88be5876c3290f4279',
            'appid'=>'f58e0cda9c414773bf2e3717459aebc7',
            'templateid'=>'458258',
            'param'=>$num,
            'mobile'=>$phone,
            'uid'=>'',
        );
        $body = json_encode($body_json);
        $header = array(
            'Accept:application/json',
            'Content-Type:application/json;charset=utf-8',
        );
        $url = 'https://open.ucpaas.com/ol/sms/sendsms';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$body);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($result,true);
        return $res;
    }

    public function rongyun($uid,$name,$imageurl){
        $appKey = config('rong.appKey');
        $appSecret = config('rong.appSecret');
        $uid = strval($uid);
        $body = "userId={$uid}&name={$name}&portraitUri={$imageurl}";
        $nonce = mt_rand();
        $timeStamp = time();
        $sign = sha1($appSecret.$nonce.$timeStamp);
        $header = array(
            'App-Key:'.$appKey,
            'Nonce:'.$nonce,
            'Timestamp:'.$timeStamp,
            'Signature:'.$sign,
            'Content-Type: application/x-www-form-urlencoded'
        );
        $url = 'http://api.cn.ronghub.com/user/getToken.json';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$body);
//    curl_setopt($ch, CURLOPT_SSL_VERI/FYPEER, false);
//    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($result,true);
        return $res;
//    var_dump($res) ;
    }

    /**
     * 获取用户此等级下的使用配置项
     * @param $length
     * @return string
     */
    function getMemberConfig($user_id)
    {
        $auth = Db::table('up_u_user')
            ->where('user_id',$user_id)
            ->value('user_auth');
        $config = Db::table('up_member_config')
            ->where('mc_auth',$auth)
            ->find();
        return $config;

    }

    /**
     * 获取用户此等级下的使用配置项
     * @param $length
     * @return string
     */
    function updateHouseList($h_type,$h_shi)
    {
        $o = Db::table('up_house')
            ->where('h_type', $h_type)
            ->where('h_shi', $h_shi)
            ->where('h_order', 2)
            ->where('h_status', 1)
            ->order('h_listtime DESC')
            ->limit(0, 30)
            ->column('h_id');
        if ($o && count($o) >= 30) {
            Db::table('up_house')
                ->where('h_type', $h_type)
                ->where('h_shi', $h_shi)
                ->where('h_order', 2)
                ->where('h_status', 1)
                ->where('h_id', 'not in', $o)
                ->update(['h_order' => 1]);
        }
        return true;

    }
    /**
     * 极光推送
     * @param $type 1:推送个人  2:推送全体
     * @param $alias 别名 user_id OR token
     * @param $message 推送消息内容
     * @param $extras 扩展字段接受数组
     * @return array
     */
    public function Jpush($type,$alias,$message,$extras)
    {
//        $alias = (string)$alias;
        import('jpush.autoload', EXTEND_PATH);
        $ji=array(
            'appKey'=>'3e7997296cf14ad4b3e80bda',
            'masterSecret'=>'9df6559e7689a26bd4cbf357',
        );
        //初始化JPushClient
        $client = new \JPush\Client($ji['appKey'],$ji['masterSecret']);
        //生成推送Payload构建器
        $push = $client->push();
        //推送平台 'all'  OR  ['ios','android']  OR  'ios','android'
        $push->setPlatform('all');
        //1:推送个人  2:推送全体
        if($type==1){
            $push->addAlias($alias);//按别名推送
        }else{
            $push->addAllAudience();//广播消息推送
        }
        //IOS推送
        $push->iosNotification($message, [
                'alert'=>$message,
                'badge' => '+1',
                'extras' => $extras,
                'sound'=>'default'
            ]
        );
        //Android推送
        $push->androidNotification($message, [
                'alert'=>$message,
                'extras' => $extras
            ]
        );
        return $push->send();
    }

    /**
     * 获取某个日期几个月后的这天
     * @param $date
     * @param $between
     * @return false|string
     */
    public function getNextMonthDays($date,$between){
        $firstday = date('Y-m-01', strtotime($date));
        $lastday = strtotime("$firstday +$between month -1 day");
        $day_lastday = date('d', $lastday); //获取下个月份的最后一天
        $day_benlastday = date('d', strtotime("$firstday +1 month -1 day")); //获取本月份的最后一天

        //获取当天日期
        $Same_day = date('d', strtotime($date));
        //判断当天是否是最后一天   或 下月最后一天 等于 本月的最后一天
        if($Same_day == $day_benlastday ||$day_lastday == $Same_day){
            $day = $day_lastday;

        }else{
            $day = $Same_day;

        }
        $day = date('Y',$lastday).'-'.date('m',$lastday).'-'.$day;

        return $day;

    }
    //-----------------------微信和支付宝支付------------------------------------

    /**
     * @param $no
     * @param $money
     * @return string
     * 支付宝支付
     */
    public function getParam($no,$money){
//    public function getParam(){
        import('alipay.aop.AopClient',EXTEND_PATH);
        import('alipay.aop.request.AlipayTradeAppPayRequest',EXTEND_PATH);
//        $no = '5851546514677777712121212';
//        $no = time().rand(1000000,9999999);
//        $money = '0.01';
        try {
            $aop = new \AopClient;
            $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";
            $aop->appId = "2019051564585666";
            $aop->rsaPrivateKey = $this->config['private_key'];
            $aop->format = "json";
            $aop->charset = "UTF-8";
            $aop->signType = "RSA2";
            $aop->alipayrsaPublicKey = $this->config['public_key'];
            $request = new \AlipayTradeAppPayRequest();
            $bizcontent = "{\"body\":\"刷新、置顶、会员\","
                . "\"subject\": \"刷新、置顶、会员购买\","
                . "\"out_trade_no\": \"" . $no . "\","
                . "\"timeout_express\": \"30m\","
                . "\"total_amount\": \"" . $money . "\","
                . "\"product_code\":\"QUICK_MSECURITY_PAY\""
                . "}";
            $request->setNotifyUrl("http://house.xuanwumobile.com/api/Order/huidiao");
            $request->setBizContent($bizcontent);
            $response = $aop->sdkExecute($request);
//            return $response;
            $res['msgsss'] = $response;
            $res['status'] = 200;
            return $res;
//            return json_encode($res);
        }catch (\Exception $e){
            $res['msgsss'] = 'error';
            $res['status'] = 0;
            return $res;
        }
    }
    public function checkReturn(){
        import('alipay.aop.AopClient',EXTEND_PATH);
        $aop = new \AopClient;
        $aop->alipayrsaPublicKey = $this->config['ali_public'];
        $flag = $aop->rsaCheckV1($_POST, NULL, "RSA2");
        if($flag){
            return $_POST;
        }else{
            return false;
        }
    }

    //-------------------------**********************微信支付***********************------------------------------------
    //-------------------------**********************微信支付***********************------------------------------------
    //-------------------------**********************微信支付***********************------------------------------------
    //-------------------------**********************微信支付***********************------------------------------------

    public function WeChatPayReady($order,$type=null){
        // 获取配置项
        $weixinpay_config2=$this->config2;
        $config2=array(
            'appid'=>$weixinpay_config2['APPID'],
            'mch_id'=>$weixinpay_config2['MCHID'],
            'nonce_str'=>'test',
            'spbill_create_ip'=>$_SERVER['REMOTE_ADDR'],
            'notify_url'=>$weixinpay_config2['NOTIFY_URL']
        );
        if(!empty($type)){
            $config2['notify_url']='http://house.xuanwumobile.com/api/Order/huidiaoWx';
        }
        // 合并配置数据和订单数据
        $data=array_merge($order,$config2);

        // 生成签名
        $sign=$this->makeSign($data);
        $data['sign']=$sign;
        $xml=$this->toXml($data);
        $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';//接收xml数据的文件
        $header[] = "Content-type: text/xml";//定义content-type为xml,注意是数组
        $ch = curl_init ($url);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);//严格校验
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        $response = curl_exec($ch);
        if(curl_errno($ch)){
            print curl_error($ch);
        }
        curl_close($ch);
        $result=$this->toArray($response);
        if($result['return_code'] == 'FAIL'){
            $returnerr['msg'] = $result['return_msg'];
            $returnerr['type'] = 'error';
            return $returnerr;
        }else{
            $result['sign']=$sign;
            $result['nonce_str']='test';
            $result2 = $this->getOrder($result['prepay_id']);
            return $result2;///
        }

    }
    /**
     * 获取时间
     * @return array
     */
    public function getDateBytimeDate($string){
        $replacement = '-';
        $replacement2 = ':';
        $a = substr_replace($string, $replacement, 4, 0);
        $b = substr_replace($a, $replacement, 7, 0);
        $c = substr_replace($b, ' ', 10, 0);
        $d = substr_replace($c, $replacement2, 13, 0);
        $e = substr_replace($d, $replacement2, 16, 0);
        return $e;
    }


    /**
     * 输出xml字符
     * @throws WxPayException
     **/
    public function toXml($data){
        //var_dump($data);
        if(!is_array($data) || count($data) <= 0){
            //throw new WxPayException("数组数据异常！");
        }
        $xml = "<xml>";
        foreach ($data as $key=>$val){
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }

    /**
     * 生成签名
     * @return 签名，本函数不覆盖sign成员变量，如要设置签名需要调用SetSign方法赋值
     */
    public function makeSign($data){
        // 去空
        $data=array_filter($data);
        //签名步骤一：按字典序排序参数
        ksort($data);
        $string_a=http_build_query($data);
        $string_a=urldecode($string_a);
        //签名步骤二：在string后加入KEY
        $config2=$this->config2;
        $string_sign_temp=$string_a."&key=".$config2['KEY'];
        //签名步骤三：MD5加密
        $sign = md5($string_sign_temp);
        // 签名步骤四：所有字符转为大写
        $result=strtoupper($sign);
        return $result;
    }

    /**
     * 将xml转为array
     * @param  string $xml xml字符串
     * @return array       转换得到的数组
     */
    public function toArray($xml){
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $result= json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $result;
    }
    //获取指定长度的随机字符串
    function getRandChar($length){
        $str = null;
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $max = strlen($strPol)-1;

        for($i=0;$i<$length;$i++){
            $str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
        }

        return $str;
    }
    //执行第二次签名，才能返回给客户端使用
    public function getOrder($prepayId){
        $data["appid"] = $this->config2["APPID"];
        $data["noncestr"] = $this->getRandChar(32);
        $data["package"] = "Sign=WXPay";
        $data["partnerid"] = $this->config2['MCHID'];
        $data["prepayid"] = $prepayId;
        $data["timestamp"] = time();
        $s = $this->makeSign($data, false);
        $data["sign"] = $s;

        return $data;
    }


    function getSignRefund($obj, $api_key)
    {
        foreach ($obj as $k => $v)
        {
            $Parameters[strtolower($k)] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        $String = $this->formatBizQueryParaMap($Parameters, false);

        //签名步骤二：在string后加入KEY
        $String = $String."&key=".$api_key;
        //签名步骤三：MD5加密
        $result = strtoupper(md5($String));
//        $result = hash_hmac("sha256",stringSignTemp,key);
        return $result;
    }

    function formatBizQueryParaMap($paraMap, $urlencode)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v)
        {
            if($urlencode)
            {
                $v = urlencode($v);
            }
            $buff .= strtolower($k) . "=" . $v . "&";
        }
        $reqPar = '';
        if (strlen($buff) > 0)
        {
            $reqPar = substr($buff, 0, strlen($buff)-1);
        }
        return $reqPar;
    }
    function postXmlCurl($xml, $url, $second=30, $useCert=false, $sslcert_path='', $sslkey_path='')
    {
        $ch = curl_init();
        //设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);
        curl_setopt($ch,CURLOPT_URL, $url);

        //设置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);

        if($useCert == true){
            curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
            curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
//            curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,TRUE);
//			curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,1);//严格校验
            //设置证书
            $path = $_SERVER['DOCUMENT_ROOT'];
            curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
            curl_setopt($ch,CURLOPT_SSLCERT, $path.'/cert/apiclient_cert.pem');
            curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
            curl_setopt($ch,CURLOPT_SSLKEY, $path.'/cert/apiclient_key.pem');
//            curl_setopt($ch,CURLOPT_CAINFO, __DIR__.'/cert/rootca.pem');
        }
        //post提交方式
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        //运行curl
        $data = curl_exec($ch);
        //返回结果
        if($data){
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
            curl_close($ch);
            return false;
        }
    }


}